package tianrun.ziguan.api.calculate.config.service.common.edit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.util.Assert;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.dto.request.common.DeleteBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.add.edit.SaveBody;
import tianrun.ziguan.api.calculate.config.entity.TCalLabelConfig;
import tianrun.ziguan.api.calculate.config.entity.TIndicatorsModule;
import tianrun.ziguan.api.calculate.config.service.cal.label.ITCalLabelConfigService;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.utils.MapUtil;
import tianrun.ziguan.api.calculate.config.utils.StringUtil;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class CalLabelConfigDealService extends AbstractDealService {

    private final ITCalLabelConfigService calLabelConfigService;

    public CalLabelConfigDealService(TGeTableConfigService tableConfigService,
                                     ITCalLabelConfigService calLabelConfigService) {
        super(tableConfigService);
        this.calLabelConfigService = calLabelConfigService;
    }

    @Override
    public void before(SaveBody body) {
        String relationTable = MapUtil.getString(body.getData(), "relation_table");
        String relationId = MapUtil.getString(body.getData(), "relation_id");
        String virtualLabel = MapUtil.getString(body.getData(), "virtual_label");
        if (StringUtil.isEmpty(virtualLabel)) return;

        LambdaQueryWrapper<TCalLabelConfig> wrapper = Wrappers.<TCalLabelConfig>lambdaQuery()
                .eq(TCalLabelConfig::getRelationId, relationId)
                .eq(TCalLabelConfig::getRelationTable, relationTable)
                .eq(TCalLabelConfig::getVirtualLabel, virtualLabel);
        if (Objects.equals(body.getOption(), SaveBody.Option.EDIT)) {
            wrapper.ne(TCalLabelConfig::getId, body.getId());
        }
        int count = calLabelConfigService.count(wrapper);
        Assert.isTrue(count == 0, "虚拟变量：" + virtualLabel + "已存在！");
    }


    @Override
    public String tableName() {
        return "t_cal_label_config";
    }

    @Override
    public void after(SaveBody body) {

    }

    @Override
    public void delBefore(DeleteBody body) {

    }

    @Override
    public void listAfter(List<Map<String, Object>> result) {

    }

    @Override
    public void delAfter(DeleteBody body) {

    }

    @Override
    public void infoAfter(Map<String, Object> bean) {

    }


}
